package com.leixiaoqiao.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

//权限过滤器
@WebFilter(urlPatterns = "/*",dispatcherTypes = {
        DispatcherType.ASYNC,
        DispatcherType.FORWARD,
        DispatcherType.REQUEST
})
public class PermissionsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将servlet请求强转为HttpServlet
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        //获取用户请求
        String requestURI = request.getRequestURI();
        //静态资源则放行
        if (    requestURI.contains("/css/")
                ||requestURI.contains("/js/")
                ||requestURI.contains("/bootstrap/")
                ||requestURI.contains("/images/")
                ||requestURI.contains("/index.jsp")
                ||requestURI.contains("/page/login.jsp")
                ||requestURI.contains("/admin")
        ){
            filterChain.doFilter(request,response);
        }else{
            //判断用户是否登录(登录则放行，没有则不放行)
            //获取session
            HttpSession session = request.getSession();
            Object successAdmin = session.getAttribute("successAdmin");
            if (!(Objects.isNull(successAdmin))){
                filterChain.doFilter(request,response);
            }else {
                request.setAttribute("msg","系统未登录，请登录！！");
               //转发到登录页面
                request.getRequestDispatcher("/page/login.jsp").forward(request,response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
